# encoding=utf-8

from PyQt5.QtWidgets import *
from PyQt5.Qt import QUrl
from PyQt5.QtCore import Qt
from call_hd1cfg import hd1RewardDlg
from call_selectsheet import selectSheetDlg

import os
import random
import ui.ui_hd1
import pandas as pd


class HD1Window(QWidget, ui.ui_hd1.Ui_Form):

	def __init__(self, parent=None):
		super(HD1Window, self).__init__(parent)
		self.m_CfgDlg = hd1RewardDlg(self)
		self.m_rewardedList = []
		self.m_selectSheetDlg = None
		self.m_excelFile = None
		self.m_selectedSheet = ""
		self.m_sheetData = {}
		self.m_sheetList = []
		self.m_rewardData = {}
		self.m_SumCnt = 0					# 总抽奖次数
		self.setupUi(self)
		self.initSignals()

	def setupUi(self, Form):
		super().setupUi(Form)
		self.rewardTableWidget.setColumnWidth(0, 150)
		self.rewardTableWidget.setColumnWidth(1, 100)

	def clear(self):
		self.m_rewardedList = []
		self.m_selectSheetDlg = None
		self.m_excelFile = None
		self.m_selectedSheet = ""
		self.m_sheetData = {}
		self.m_SumCnt = 0
		self.m_sheetList = []
		self.m_rewardData = {}
		self.rewardTableWidget.setRowCount(0)

	def clearUi(self):
		self.fileLineEdit.setText("")

	def initSignals(self):
		self.fileChooseBtn.clicked.connect(self.openFile)
		self.startLotteryBtn.clicked.connect(self.startLottery)
		self.cfgBtn.clicked.connect(self.openCfg)
		self.exportListBtn.clicked.connect(self.exportList)
		self.resetLotteryBtn.clicked.connect(self.resetLottery)

	def openFile(self):
		lstFilePath, _ = QFileDialog.getOpenFileNames(self, "选择表格文件", filter="Excel文件(*.xls *.xlsx *.csv)")
		if not lstFilePath:
			return
		filePath = lstFilePath[0]
		self.fileLineEdit.setText(filePath)
		self.m_excelFile = pd.ExcelFile(filePath)
		lstSheetName = list(pd.read_excel(self.m_excelFile, sheet_name=None))
		self.m_selectSheetDlg = selectSheetDlg(self, lstSheetName)
		self.m_selectSheetDlg.show()

	def cbSelectedSheet(self):
		df = pd.read_excel(self.m_excelFile, self.m_selectedSheet)
		# 对于每一行，通过列名name访问对应的元素
		for row in df.itertuples():
			self.m_sheetData[getattr(row, "序号")] = getattr(row, "淘宝id")
		self.m_sheetList = list(self.m_sheetData)

	def openCfg(self):
		self.m_CfgDlg.show()

	def validStartLottery(self):
		if not self.fileLineEdit.text():
			QMessageBox.information(self, "提示", "请选择文件", QMessageBox.Yes)
			return False
		if not self.m_CfgDlg.m_CfgInfo:
			QMessageBox.information(self, "提示", "请添加奖品", QMessageBox.Yes)
			return False
		if not self.m_CfgDlg.m_CfgList:
			QMessageBox.information(self, "提示", "奖品已抽完", QMessageBox.Yes)
			return False
		return True

	def startLottery(self):
		if not self.validStartLottery():
			return
		for _, iCnt in self.m_CfgDlg.m_CfgList:
			self.m_SumCnt += iCnt
		if not self.m_SumCnt:
			QMessageBox.information(self, "提示", "奖品已抽完", QMessageBox.Yes)
			return
		for _ in range(self.m_SumCnt):
			self.trueStartLottery()
		self.m_SumCnt = 0

	def trueStartLottery(self):
		lstCfg = self.m_CfgDlg.m_CfgList
		sReward, iCnt = lstCfg[0]
		if not iCnt:
			lstCfg.pop(0)
			if not lstCfg:
				QMessageBox.information(self, "提示", "奖品已抽完", QMessageBox.Yes)
				return
			sReward, iCnt = lstCfg[0]
		iCnt -= 1
		lstCfg[0] = [sReward, iCnt]
		iRandom = random.sample(self.m_sheetList, 1)[0]
		self.m_sheetList.remove(iRandom)
		self.m_rewardData[iRandom] = (str(iRandom), sReward)
		self.insertRewardTbl(iRandom)

	def insertRewardTbl(self, iRandom):
		sRandom, sReward = self.m_rewardData[iRandom]
		iRow = self.rewardTableWidget.rowCount()
		self.rewardTableWidget.setRowCount(iRow + 1)

		idItem = QTableWidgetItem(sRandom)
		idItem.setFlags(idItem.flags() & Qt.ItemIsEditable)

		rewardItem = QTableWidgetItem(sReward)
		rewardItem.setFlags(rewardItem.flags() & Qt.ItemIsEditable)

		self.rewardTableWidget.setItem(iRow, 0, idItem)
		self.rewardTableWidget.setItem(iRow, 1, rewardItem)

	def validExport(self):
		if not self.m_rewardData:
			QMessageBox.information(self, "提示", "当前没有中奖名单", QMessageBox.Yes)
			return False
		return True

	def exportList(self):
		if not self.validExport():
			return
		directUrl = QFileDialog.getExistingDirectoryUrl(self, "选择输出文件夹", QUrl()).toLocalFile()
		if not directUrl:
			return
		df = pd.DataFrame(self.m_rewardData.values(), columns=["售后卡编码", "中奖情况"])
		filePath = f"{directUrl}/{self.m_selectedSheet}.csv"
		df.to_csv(filePath, index=False, encoding="utf-8-sig")

		msgBox = QMessageBox(self)
		msgBox.setWindowTitle("导出名单")
		msgBox.setText(f"导出中奖名单成功!\n文件路径为{filePath}")
		openPathBtn = msgBox.addButton(self.tr("打开文件位置"), QMessageBox.AcceptRole)
		msgBox.addButton(self.tr("确认"), QMessageBox.YesRole)
		msgBox.exec()
		if msgBox.clickedButton() == openPathBtn:
			filepath = filePath.replace('/', '\\')
			os.popen(f"explorer /select, {filepath}")

	def resetLottery(self):
		answer = QMessageBox.information(self, "提示", "确认重置所有数据吗", QMessageBox.Yes | QMessageBox.No)
		if answer == QMessageBox.Yes:
			self.trueResetLottery()
			QMessageBox.information(self, "成功", "重置成功", QMessageBox.Yes)

	def trueResetLottery(self):
		self.clear()
		self.clearUi()
		self.m_CfgDlg.clear()
		self.m_CfgDlg.clearUi()
